import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


public class Broadcaster extends Thread {
	InetAddress address;
	DatagramSocket socket;
	int port;
	
	public Broadcaster(int port){
		
		this.port=port;
		try{
			socket=new DatagramSocket();
			address = InetAddress.getByName("230.0.0.1");
		}catch(UnknownHostException e){
			e.printStackTrace();
		}catch(SocketException e){
			e.printStackTrace();
		}
		
	}
	
	public void run(){
		System.out.println("Broadcaster broadcasts at port " + this.port);
		while(true){
			broadcast();
			try{				
				Thread.sleep(1000);
			}catch(InterruptedException e){
				e.printStackTrace();
			}			
		}		
	}
	
	public void broadcast(){
		try{			
			
						
			User u=NetworkManager.getInstance().getOperatingUser();
					
			//Serialize user into byte[]
			byte[] buf;
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			ObjectOutputStream oos=new ObjectOutputStream(baos);
			oos.writeObject(u);
			buf=baos.toByteArray();
			oos.close();
			baos.close();			
			
			DatagramPacket packet = new DatagramPacket(buf, buf.length,address,this.port);
			socket.send(packet);
			
			//System.out.println("Broadcast id at " + java.util.Calendar.getInstance().getTime().toString());
			
		}catch(UnknownHostException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}

}
